package com.ym.pms.controller;


import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.ym.pms.model.Comments;
import com.ym.pms.service.CommentsServices;
import com.ym.pms.utils.JSONResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import io.swagger.annotations.ApiResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;

/**
 * @Author ming
 * @Description
 * @Date 2020/12/16/016 20:56
 **/
@RestController
@Api(tags = "留言接口")
@RequestMapping("/comments")
public class CommentsController {

    @Autowired
    CommentsServices commentsServices;


    @ApiOperation(value = "获取指定用户收到的所有留言",notes = "id为0，是系统自动发送的信息")
    @GetMapping("/receive")
    public JSONResult findByUserId(Integer id, Integer pageNum, Integer pageSize)
    {
        PageHelper.startPage(pageNum,pageSize);
        List<Comments> Comments = commentsServices.findByReceiverId(id);
        PageInfo pageInfo = new PageInfo(Comments);
        return JSONResult.ok(pageInfo);
    }

    @ApiOperation("获取指定用户发送的所有留言")
    @GetMapping("/send")
    public JSONResult findByAdminId(Integer id, Integer pageNum, Integer pageSize){
        PageHelper.startPage(pageNum,pageSize);
        List<Comments> Comments = commentsServices.findBySenderId(id);
        PageInfo pageInfo = new PageInfo(Comments);
        return JSONResult.ok(pageInfo);
    }


    @ApiOperation(value = "添加留言",notes = "无需填写adminName,createTime，id,isRead,userName")
    @PostMapping
    @ApiResponse(code = 400,message = "数据验证失败，msg为详情字段")
    public JSONResult add(@Valid Comments comments, BindingResult bindingResult){
        for (ObjectError error : bindingResult.getAllErrors()) {
            return JSONResult.build(400,error.getDefaultMessage(),null);
        }
        commentsServices.add(comments);
        return JSONResult.ok();
    }

    @ApiOperation("查看留言具体内容")
    @GetMapping("/{id}")
    public JSONResult read(@ApiParam("留言id") @PathVariable("id") Integer id){
//        将留言设为已读
        commentsServices.read(id);
        System.out.println(id);
        return JSONResult.ok(commentsServices.findById(id));
    }


    @ApiOperation("删除留言")
    @DeleteMapping("/{id}")
    public JSONResult del(@PathVariable("id") @ApiParam("留言id") Integer id){
        commentsServices.del(id);
        return JSONResult.ok();
    }

}
